

//交作业用EventBus

package com.example.ball;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity2 extends AppCompatActivity {
    private TextView textView;
    private Handler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        // 初始化textView
        textView = (TextView) findViewById(R.id.tvTime);

        // 创建Handler实例
        myHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // 当接收到消息时更新UI
                // textView.setText(String.valueOf(msg.what));
                textView.setText(msg.obj.toString());
            }
        };

        // 创建并启动线程
        MyThread myThread = new MyThread();
        myThread.start(); // 使用start()方法来启动线程，而不是run()
    }

    class MyThread extends Thread {
        private int times = 0;

        @Override
        public void run() {
            while (times >=0) {
                try {
                    Thread.sleep(1000); // 延时1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 获取当前时间
                Calendar date = Calendar.getInstance();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) + 1;
                int day = date.get(Calendar.DAY_OF_MONTH);
                int hour = date.get(Calendar.HOUR_OF_DAY);
                int minute = date.get(Calendar.MINUTE);
                int second = date.get(Calendar.SECOND);

                // 格式化时间字符串
                String dateTime = String.format("%04d年%02d月%02d日\n%02d:%02d:%02d",
                        year, month, day, hour, minute, second);

                // 创建消息对象
                Message msg = new Message();
                msg.what = 1; // 可以使用what字段来传递信息类型
                msg.obj = dateTime; // 可以使用obj字段来传递任意对象

                // 发送消息给Handler处理
                myHandler.sendMessage(msg);

                times++; // 更新计数

            }
        }
    }
}
